package com.coldwindblows.blog.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.coldwindblows.blog.constant.WebConst;
import com.coldwindblows.blog.dao.ContentMapper;
import com.coldwindblows.blog.dto.Types;
import com.coldwindblows.blog.exception.TipException;
import com.coldwindblows.blog.pojo.ContentDo;
import com.coldwindblows.blog.service.IContentService;
import com.coldwindblows.blog.service.IMetaService;
import com.coldwindblows.blog.service.IRelationshipService;
import com.coldwindblows.blog.utils.TaleUtils;
import com.coldwindblows.blog.utils.Tools;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vdurmont.emoji.EmojiParser;

@Service
public class IContentServiceImpl implements IContentService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(IContentServiceImpl.class);
	
	@Autowired
	private ContentMapper contentDao;
	
	@Autowired
	private IRelationshipService relationshipService;
	
	@Autowired
	private IMetaService metaService;
	
	@Override
	public String publish(ContentDo contents) {
		if(null == contents) {
			return "文章对象为空";
		}
		if(StringUtils.isBlank(contents.getTitle())) {
			return "文章标题不能为空";
		}
		if(StringUtils.isBlank(contents.getContent())) {
			return "文章内容不能为空";
		}
		int titleLength = contents.getTitle().length();
		if(titleLength > WebConst.MAX_TITLE_COUNT) {
			return "文章标题过长";
		}
		int contentLength = contents.getContent().length();
		if(contentLength > WebConst.MAX_TEXT_COUNT) {
			return "文章内容过长";
		}
		if(null == contents.getAuthorId()) {
			return "请登录后发布文章";
		}
		if(StringUtils.isNotBlank(contents.getSlug())) {
			if(contents.getSlug().length() < WebConst.MIN_SLUG_COUNT) {
				return "路径太短了";
			}
			if(!TaleUtils.isPath(contents.getSlug())) {
				return "您输入的路径不合法";
			}
			Integer count = contentDao.countByTypeAndSlug(contents.getType(), contents.getSlug());
			if(count > 0) {
				return "该路径已存在，请重新输入";
			}
		} else {
			contents.setSlug(null);
		}
		
		contents.setContent(EmojiParser.parseToAliases(contents.getContent()));
		contents.setCreated(new Date());
		contents.setModified(new Date());
		contents.setHits(0);
		contents.setCommentsNum(0);
		
		String tags = contents.getTags();
		String categories = contents.getCategories();
		contentDao.insert(contents);
		Integer cid = contents.getCid();
		metaService.insertMetas(cid, tags, Types.TAG.getType());
		metaService.insertMetas(cid, categories, Types.CATEGORY.getType());
		
		return WebConst.SUCCESS_RESULT;
	}

	@Override
	public PageInfo<ContentDo> getContents(int page, int pageSize) {
		LOGGER.debug("Enter getContents method");
		ContentDo temp = new ContentDo();
		temp.setType(Types.ARTICLE.getType());
		temp.setStatus(Types.PUBLISH.getType());
		PageHelper.startPage(page, pageSize);
		List<ContentDo> list = contentDao.selectBySelective(temp);
		PageInfo<ContentDo> pageList = new PageInfo<>(list);
		LOGGER.debug("Exit getContents method");
		return pageList;
	}

	/**
	 * 根据id或者slug查询
	 */
	@Override
	public ContentDo getDetail(String id) {
		if(StringUtils.isBlank(id)) {
			return null;
		}
		ContentDo content = null;
		if(Tools.isNumber(id)) {
			content = contentDao.selectByPrimaryKey(Integer.valueOf(id));
			return content;
		}
		content = new ContentDo();
		content.setSlug(id);
		List<ContentDo> list = contentDao.selectBySelective(content);
		if(list.size() != 1) {
			throw new TipException("query content by id and return is not one");
		}
		
		return list.get(0);
	}

	@Override
	public boolean updateContent(ContentDo content) {
		if(null == content || null == content.getCid()) {
			return false;
		}
		
		return contentDao.updateByPrimaryKey(content) > 0;
	}

	@Override
	public PageInfo<ContentDo> getArticles(Integer mid, int page, int pageSize) {
		int total = contentDao.countByMid(mid);
		PageHelper.startPage(page, pageSize);
		List<ContentDo> list = contentDao.findByCatalog(mid);
		PageInfo<ContentDo> pageList = new PageInfo<>(list);
		pageList.setTotal(total);
		
		return pageList;
	}

	@Override
	public PageInfo<ContentDo> getArticles(String keyword, int page, int pageSize) {
		PageHelper.startPage(page, pageSize);
		ContentDo contentDo = new ContentDo();
		contentDo.setType(Types.ARTICLE.getType());
		contentDo.setStatus(Types.PUBLISH.getType());
		contentDo.setTitle("%" + keyword + "%");
		List<ContentDo> list = contentDao.selectBySelective(contentDo);
		
		return new PageInfo<>(list);
	}

	@Override
	public PageInfo<ContentDo> getArticlesWithPage(ContentDo content, int page, int pageSize) {
		PageHelper.startPage(page, pageSize);
		List<ContentDo> list = contentDao.selectBySelective(content);
		
		return new PageInfo<>(list);
	}

	@Transactional
	@Override
	public String deleteContent(Integer cid) {
		ContentDo content = this.getDetail(cid.toString());
		if(null == content) {
			return "数据为空";
		}
		contentDao.deleteByPrimaryKey(cid);
		relationshipService.deleteById(cid, null);
		
		return WebConst.SUCCESS_RESULT;
	}

	@Transactional
	@Override
	public String updateArticle(ContentDo content) {
		if(null == content) {
			return "文章对象为空";
		}
		if(StringUtils.isBlank(content.getTitle())) {
			return "文章标题不能为空";
		}
		if(StringUtils.isBlank(content.getContent())) {
			return "文章内容不能为空";
		}
		int titleLength = content.getTitle().length();
		if(titleLength > WebConst.MAX_TITLE_COUNT) {
			return "文章标题过长";
		}
		int contentLength = content.getContent().length();
		if(contentLength > WebConst.MAX_TEXT_COUNT) {
			return "文章内容过长";
		}
		if(null == content.getAuthorId()) {
			return "请登录后发布文章";
		}
		if(StringUtils.isBlank(content.getSlug())) {
			content.setSlug(null);
		}
		content.setModified(new Date());
		Integer cid = content.getCid();
		content.setContent(EmojiParser.parseToAliases(content.getContent()));
		
		contentDao.updateByPrimaryKey(content);
		relationshipService.deleteById(cid, null);
		metaService.insertMetas(cid, content.getTags(), Types.TAG.getType());
		metaService.insertMetas(cid, content.getCategories(), Types.CATEGORY.getType());
		
		return WebConst.SUCCESS_RESULT;
	}

	@Transactional
	@Override
	public boolean updateCategory(String ordinal, String newCatefory) {
		ContentDo content = new ContentDo();
		content.setCategories(newCatefory);
		content.setTitle(ordinal);
		
		return contentDao.updateCategoriesByOldCate(content) > 0;
	}

}
